<template>
  <div class="app-container">
    <a-row style="display: flex;height: 100%">
      <a-col :span="15" ref="leftColumn" style="display: flex;
      flex-direction: column;">
        <a-row style="">
          <a-col :span="24">
            <div class="div1" style="margin: 0px 10px 10px 0px;background-color: white;padding: 10px">
              <div class="search-area">
                <a-button-group>
                  <a-button style="margin-right: 10px"
                            :class="{ 'active-button': selectedButtonType === 'date' }"
                            @click="setDateType('date')"
                  >按日</a-button>
                  <a-button style="margin-right: 10px"
                            :class="{ 'active-button': selectedButtonType === 'month' }"
                            @click="setDateType('month')"
                  >按月</a-button>
                  <a-button style="margin-right: 10px"
                            :class="{ 'active-button': selectedButtonType === 'year' }"
                            @click="setDateType('year')"
                  >按年</a-button>
                </a-button-group>
                <label style="margin-right: 5px">查询时间</label>
                <a-range-picker
                />
              </div>
              </div>
          </a-col>
        </a-row>
        <a-row style="">
          <a-col :span="24">
            <div class="div2" style="margin: 0px 10px 10px 0px;background-color: white;">
              <div class="header-container">
                <img src="@/assets/image/messageStatistic/icon-title.png"/>
                <span style="text-align: left; font-weight: bold">消息概览</span>
              </div>
              <div class="stats-area" >
                <a-card style=" border: none;cursor: pointer;display: flex " @click="onOverViewDetail('text')">
                  <img src="@/assets/image/messageStatistic/icon-1.png">
                  <a-statistic title="文本消息" v-model:value="overviewData.textMessages" class="custom-statistic" value-style="color:#F4C771FF">
                    <template #suffix>
                      <span style="font-size: 10px;color: black" >个</span>
                    </template>
                  </a-statistic>
                </a-card>
                <a-card style="border: none;cursor: pointer" @click="onOverViewDetail('image')">
                  <img src="@/assets/image/messageStatistic/icon-2.png">
                  <a-statistic title="图片消息" v-model:value="overviewData.imageMessages" class="custom-statistic" value-style="color:#fd7b73">
                    <template #suffix>
                      <span style="font-size: 10px;color: black">个</span>
                    </template>
                  </a-statistic>
                </a-card>
                <a-card style="border: none;cursor: pointer"  @click="onOverViewDetail('voice')">
                  <img src="@/assets/image/messageStatistic/icon-3.png">
                  <a-statistic title="语音消息" v-model:value="overviewData.voiceMessages" class="custom-statistic" value-style="color:#4A7BFEFF">
                    <template #suffix>
                      <span style="font-size: 10px;color: black">个</span>
                    </template>
                  </a-statistic>
                </a-card>
                <a-card style="border: none;cursor: pointer" @click="onOverViewDetail('video')">
                  <img src="@/assets/image/messageStatistic/icon-4.png">
                  <a-statistic title="视频消息" v-model:value="overviewData.videoMessages" class="custom-statistic" value-style="color:#4FCC87FF">
                    <template #suffix>
                      <span style="font-size: 10px;color: black">个</span>
                    </template>
                  </a-statistic>
                </a-card>
                <a-card style="border: none;cursor: pointer" @click="onOverViewDetail('file')">
                  <img src="@/assets/image/messageStatistic/icon-5.png">
                  <a-statistic title="文件消息" v-model:value="overviewData.fileMessages" class="custom-statistic" value-style="color:#FBB011FF">
                    <template #suffix>
                      <span style="font-size: 10px;color: black">个</span>
                    </template>
                  </a-statistic>
                </a-card>
              </div>
            </div>
          </a-col>
        </a-row>
        <a-row style="">
          <a-col :span="24">

            <div class="div3" style="margin: 0px 10px 10px 0px;background-color: white;">
              <div class="header-container">
                <img src="@/assets/image/messageStatistic/icon-title.png"/>
                <span style="text-align: left;font-weight: bold">消息发送统计</span>
              </div>
              <div  class="bar-chart-area" id="chartL1" >

              </div>
            </div>

          </a-col>
        </a-row>
        <a-row  style="flex: 1;display: flex">
          <a-col :span="16" style=";display: flex">
            <div class="div4" style="margin: 0px 10px 10px 0px;background-color: white;flex: 1;">
              <div class="header-container">
                <img src="@/assets/image/messageStatistic/icon-title.png"/>
                <span style="text-align: left;font-weight: bold">群组发展趋势</span>
                <a-button type="primary" style="margin-left: auto;height: 26px;text-align: center;" @click="onGroupInfoDetail()">查看更多</a-button>
              </div>
              <div class="line-chart-area" id="chartL2">

              </div>
            </div>
          </a-col>
          <a-col :span="8" style="display: flex">
            <div class="div5" style="margin: 0px 10px 10px 0px;background-color: white;flex: 1">
              <div class="header-container">
                <img src="@/assets/image/messageStatistic/icon-title.png"/>
                <span style="text-align: left;font-weight: bold">活跃群组TOP5</span>
              </div>

              <div class="list-area" id="chartL3">

              </div>
            </div>
          </a-col>
        </a-row>
      </a-col>
      <a-col :span="9" style="display: flex;flex-direction: column;" >
        <a-row >
          <a-col :span="24" ref="rightColumn">
            <div class="div6" ref="div6" style="margin: 0px 0px 10px 0px;background-color: white;">
              <div class="header-container">
                <img src="@/assets/image/messageStatistic/icon-title.png"/>
                <span style="text-align: left;font-weight: bold">部门人员占比</span>
                <div class="div8">
                  <label style="width: 100px;padding-left: 100px;">部门选择</label>
                  <a-tree-select v-model:value="searchData.orgId" style="width: 260px;padding-left: 20px" @change="onSearch" allow-clear placeholder="抚州市公安局" :height="400"
                                 tree-data-simple-mode
                                 :tree-data="treeData" tree-default-expand-all
                                 :field-names="{ children: 'children', label: 'name', value: 'id' }">
                  </a-tree-select>
                </div>
              </div>
              <div class="pie-chart-area" id="chartL4" >
              </div>
            </div>
          </a-col>
        </a-row>
        <a-row style="flex: 1;display: flex" >
          <a-col :span="24" style="flex: 1;display: flex">
            <div class="div7" style="background-color: white;flex: 1;display: flex ; flex-direction: column;margin-bottom: 10px;">
              <div class="header-container">
                <img src="@/assets/image/messageStatistic/icon-title.png"/>
                <span style="text-align: left;font-weight: bold">人员信息</span>
              </div>
              <div class="table-container" ref="tableContainer" >
              <a-table :bordered="false" :data-source="tableData.data" :columns="tableData.columns"
                       :loading="tableData.loading" :pagination="false"
                       class="table-class"   size="middle"
                       :style="{ backgroundColor: '#f5f7fa' }"
                       style="position: relative;z-index: 1;overflow: hidden;background-repeat: no-repeat;background-position: bottom right;background-size: auto;font-size: 16px;height: 100%"
              >
                <template v-slot:bodyCell="{ column, record, index}">
                  <template v-if="column.dataIndex === 'avatar'">
                    <img :src="record.img" alt="Avatar" style="width: 40px; height: 40px; border-radius: 100%;"/>
                  </template>
                  <template v-if="column.dataIndex === 'alarm'">
                    <span  style="font-family:YouSheBiaoTiHei; font-size: 30px; color: #2782ee">{{ record.alarm }}</span>
                  </template>
                  <template v-if="column.dataIndex === 'name'"> <!-- 定义姓名字段的显示方式 -->
                    <span>{{ record.name.length > 5 ? record.name.substring(0, 5) + '...' : record.name }}</span>
                  </template>
                </template>
              </a-table>
              </div>
              <div style="display: flex; justify-content: flex-end;margin-top: 10px">
                <a-pagination :current="pagerData.current" :pageSize="pagerData.pageSize" :total="pagerData.total" :show-total="total => '共' + total + '条'"
                              @showSizeChange="onPagerSizeChange" @change="onPagerChange"  >
                </a-pagination>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-col>
    </a-row>

    <!-- 弹窗组件 -->
    <message-over-view-detail
      v-if="modalData.showoverviewdetail"
      :modalParam="modalData.data"
      :messageType="modalData.messageType"
      :range="modalData.range"
      @close="closeModal('showoverviewdetail', $event)">
    </message-over-view-detail>

    <GroupInfoDetail
      v-if="modalData.showgroupinfodetail"
      :modalParam="modalData.data"
      :range="modalData.range"
      @close="closeModal('showgroupinfodetail', $event)">
    </GroupInfoDetail>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from 'dayjs';
import MessageOverViewDetail from "@/views/chat/messageStatistic/MessageOverViewDetail.vue";
import GroupInfoDetail from "@/views/chat/messageStatistic/GroupInfoDetail.vue";
export default {
  name: 'MessageStatistic',
  components: {
    GroupInfoDetail, MessageOverViewDetail,
  },

  data() {
    return {
      dateType: 'month',
      currentDept: '全部', // 当前选择的部门
      selectedDept:'全部',//已选中的部门
      selectedButtonType:'month',
      datePickerType: 'month', // 添加 picker 属性的绑定
      datePickerConfig: {}, // 添加 picker-options 属性的绑定

      treeData: [],
      tableData: {
        loading: false, selectedRowKeys: [], data: [],
        columns: [
          {
            title: '头像',
            dataIndex: 'avatar',
            key: 'avatar',
            scopedSlots: {customRender: 'avatar'},
            align: "center",
            width:100
          },
          {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            align: "center",
            width:100,
            scopedSlots: { customRender: 'name' }, // 使用自定义渲染
            className: 'column-name', // 使用class来控制样式
          },
          {
            title: '部门名称',
            dataIndex: 'orgName',
            key: 'orgName',
            align: "center",
            width:300
          },
          {
            title: '手机号',
            dataIndex: 'alarm',
            key: 'alarm',
            align: "center",
            width:200
          }
        ],
      },
      pagerData: {
        current: 1, pageSize: 5, total: 0
      },


      modalData: {
        showoverviewdetail: false,
        showgroupinfodetail:false,
        messageType:'',//消息类型
        range: [null, null], // 起始时间和终止时间的数组
        data: null
      },

      searchData: {
        orgId: '',
        range: getDefaultDateRange('month'),//时间查询条件
        dt: dayjs().format('YYYY-MM-DD'),
      },
      _chart:null,
      overviewData:{
        loading: false,
        data: [],
        textMessages: 1123,
        imageMessages: 240,
        voiceMessages: 420,
        videoMessages: 60,
        fileMessages:50,
      },
    };
  },
  mounted() {
    this.queryOverViewData();
    this.queryPageData();
    this.queryTableList();
    this.initChartL4();
    // this.adjustTableHeight(); // 初次加载时调整表格高度
    window.addEventListener('resize', this.handleResize);// 监听窗口大小变化
    this.$nextTick(() => {
      console.log("正在初始化图表...");
      // 在下一次 DOM 更新循环结束之后执行
      this.initChartL1();
      this.initChartL2();
      this.initChartL3();
    });


  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize); // 移除监听器
    // window.removeEventListener('resize', this.adjustTableHeight); // 移除监听器

  },

  methods: {

    handleResize() {
      this.initChartL1();
      this.initChartL2();
      this.initChartL3();
      this.initChartL4();
      // this.adjustTableHeight();   // 调整表格高度

    },
    //消息概览弹窗
    onOverViewDetail(text){
      this.modalData.showoverviewdetail = false;
      this.$nextTick(() => {
        this.modalData.messageType = text;
        this.modalData.data = {
          modalTitle: "消息概览",
          contentType: text,// 将消息类型存储在 modalData 中
          range:this.searchData.range
        };
        this.modalData.showoverviewdetail = true;
      });
    },
    //群组发展趋势弹窗
    onGroupInfoDetail(){
      this.modalData.showgroupinfodetail = false;
      this.$nextTick(() => {
        this.modalData.data = {
          modalTitle: "群组发展趋势",
          range:this.searchData.range
        };
        this.modalData.showgroupinfodetail = true;
      });
    },

    //关闭弹窗
    closeModal(type, data) {
      this.modalData.data = null;
      this.modalData[type] = false;
      if (data && data.refresh) {
        //this.onSearch();
      }
    },

    //部门人员查询
    onSearch() {
      this.pagerData.current = 1;
      this.queryTableList();
      this.queryDeptPercentage();
      this.initChartL4();
    },

    //获取机构选择器数据
    queryPageData() {
      let params = {

      }
      this.$ajax.post(this.$Api.orgData.queryOrgDataSyncTreeList, params).then(res => {
        if (res.data.code == 200) {
          this.treeData = _.cloneDeep(res.data.data);
        }
      })
    },

    //获取人员信息列表
    queryTableList() {
      let params = {
        orgId: this.searchData.orgId,
        limit: this.pagerData.pageSize,
        page: this.pagerData.current,
      }
      if(!this.searchData.orgId||this.searchData.orgId==''){
        params.orgId = "0001"
      }
      this.tableData.loading = true;
      this.$ajax.post(this.$Api.employeeData.queryEmployeeDataPager, params).then(res => {
        if(res.data.code == 200) {
          //设置表格数据
          this.tableData.data = res.data.data;
          //设置分页数据
          this.pagerData.total = res.data.count;
        }
        return [];
      }).finally(() => {
        this.tableData.loading = false;
      })
    },

    setDateType(type) {
      this.dateType = type;
      //this.searchData.range = getDefaultDateRange(type);
      this.selectedButtonType = type; // 更新选中的按钮类型
      // 根据按钮类型设置日期范围和日期选择器配置
      switch (type) {
        case 'date':
          // 当点击按日按钮时，时间选择器的范围设置为当前日期所在的月份
          this.searchData.range = [dayjs().startOf('month'), dayjs().endOf('month')];
          this.datePickerConfig = {
            showTime: false,
            format: 'YYYY-MM-DD',
          };
          this.datePickerType = 'date';
          break;
        case 'month':
          // 当点击按月按钮时，时间选择器的范围设置为当前月份往前推一年
          this.searchData.range = [dayjs().subtract(1, 'year').startOf('month'), dayjs().endOf('month')];
          this.datePickerConfig = {
            showTime: false,
            format: 'YYYY-MM',
          };
          this.datePickerType = 'month';
          break;
        case 'year':
          // 当点击按年按钮时，时间选择器的范围设置为当前年份往前推5年
          this.searchData.range = [dayjs().subtract(5, 'year').startOf('year'), dayjs().endOf('year')];
          this.datePickerConfig = {
            showTime: false,
            format: 'YYYY',
          };
          this.datePickerType = 'year';
          break;
        default:
          this.searchData.range = [null, null];
          this.datePickerConfig = {
            showTime: false,
            format: 'YYYY-MM-DD',
          };
      }
      this.queryOverViewData();
      this.initChartL1();
      this.initChartL2();
      this.initChartL3();

    },

    //处理时间选择器时间变化
    handleChange(dates, dateStrings) {
      console.log(dates, dateStrings);
      // 每次时间选择器的时间发生变化时，立即执行查询操作
      this.queryOverViewData();
      this.initChartL1();
      this.initChartL2();
      this.initChartL3();
    },

    //获取消息概览部分数据
    queryOverViewData(){
      // 构建请求参数
      let params = {
        begin:null,
        end:null,
      };
      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      // 构建 URL 字符串
      let url = `${this.$Api.messageStatisticData.queryOverView}?${new URLSearchParams(params).toString()}`;
      this.$ajax.get(url).then(res => {
            if(res.data.code == 0) {
              // 记录接收到的数据
              console.log('接收到的数据:', res.data.result);
              //设置消息概览处数据
              // 将后端返回的数据设置到overviewData中
              this.overviewData = {
                textMessages: res.data.result.textMessageCount,
                imageMessages: res.data.result.imageMessageCount,
                voiceMessages: res.data.result.audioMessageCount,
                videoMessages: res.data.result.videoMessageCount,
                fileMessages: res.data.result.fileMessageCount,
              };
            }})
    },

    //获取消息发送统计数据
    queryMessageSender(){
      // 构建请求参数
      let params = {
        begin:null,
        end:null,
      };
      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      // 构建 URL 字符串
      let url = '';

      if (this.selectedButtonType === 'month') {
         url = `${this.$Api.messageStatisticData.queryMessageSender}?${new URLSearchParams(params).toString()}`;
      }
      if (this.selectedButtonType === 'date') {
         url = `${this.$Api.messageStatisticData.queryMessageSenderByDate}?${new URLSearchParams(params).toString()}`;
      }
      if (this.selectedButtonType === 'year') {
         url = `${this.$Api.messageStatisticData.queryMessageSenderByYear}?${new URLSearchParams(params).toString()}`;
      }
      // 返回一个 Promise 对象
      return this.$ajax.get(url).then(res => {
        if(res.data.code == 0) {
          // 记录接收到的数据
          console.log('接收到的数据:', res.data.result);
          // 返回数据
          return res.data.result;
        }})
    },

    //获取群组环比同比增长率数据
    queryGrowGroupRateData(){
      // 构建请求参数
      let params = {
        begin:null,
        end:null,
      };
      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      // 构建 URL 字符串
      let url = '';

      if (this.selectedButtonType === 'month') {
        url = `${this.$Api.messageStatisticData.queryGrowGroupDataMonth}?${new URLSearchParams(params).toString()}`;
      }
      if (this.selectedButtonType === 'date') {
        url = `${this.$Api.messageStatisticData.queryGrowGroupDataDay}?${new URLSearchParams(params).toString()}`;
      }
      if (this.selectedButtonType === 'year') {
        url = `${this.$Api.messageStatisticData.queryGrowGroupDataYear}?${new URLSearchParams(params).toString()}`;
      }
      // 返回一个 Promise 对象
      return this.$ajax.get(url).then(res => {
        if(res.data.code == 0) {
          // 记录接收到的数据
          console.log('接收到的同比环比数据:', res.data.result);
          // 返回数据
          return res.data.result;
        }})
    },

    //获取活跃群组数据
    queryActiveGroupData(){
      // 构建请求参数
      let params = {
        begin:null,
        end:null,
      };
      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      // 构建 URL 字符串
      let url = `${this.$Api.messageStatisticData.queryActiveGroupData}?${new URLSearchParams(params).toString()}`;
      // 返回一个 Promise 对象
      return this.$ajax.get(url).then(res => {
        if(res.data.code == 0) {
          // 记录接收到的数据
          console.log('接收到的数据:', res.data.result);
          // 返回数据
          return res.data.result;
        }})

    },

    //获取部门人员占比数据
    queryDeptPercentage() {
      // 构建请求参数
      let params = {
        orgId:this.searchData.orgId
      };
      if(!this.searchData.orgId||this.searchData.orgId=='抚州市公安局'){
        params.orgId = "0001"
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      let url = `${this.$Api.messageStatisticData.queryOrgEmpData}?${new URLSearchParams(params).toString()}`;
      return this.$ajax.get(url).then(res => {
        if (res.data.code === 0) {
          this.allDepts = res.data.result; // 保存原始全部部门数据
          return res.data.result;
        }
      });
      console.log(this.allDepts)
    },

    //分页页码改变
    onPagerChange(current) {
      this.pagerData.current = current;
      this.queryTableList();
    },
    //分页每页数量改变
    onPagerSizeChange(current, size) {
      this.pagerData.current = 1;
      this.pagerData.pageSize = size;
      this.queryTableList();
    },

    //初始化左侧柱状图
    initChartL1() {
      // 保存正确的上下文
      const self = this;
      // 直接初始化，不需要检查实例是否存在
      document.getElementById("chartL1").removeAttribute('_echarts_instance_');
      let chartL1 = document.getElementById("chartL1");
      const windowHeight = window.innerHeight; // 获取窗口高度
      chartL1.style.height = `${windowHeight * 0.3}px`;
      const chart = echarts.init(chartL1);

      // 在这里调用 queryMessageSender 方法获取数据
      this.queryMessageSender().then(result => {
        let xAxisData;
        switch (self.selectedButtonType) {

          case 'date':
            // 如果选择按日，横坐标为月-日
            xAxisData = result.map(item => dayjs(item.date).format("MM-DD"));
            break;
          case 'month':
            // 如果选择按月，横坐标为年-月
            xAxisData = result.map(item => `${item.year}-${item.month}`);
            break;
          case 'year':
            // 如果选择按年，横坐标为年
            xAxisData = result.map(item => item.year);
            break;
          default:
            xAxisData = [];
        }

        const option = {
          color: ['#DEC4E1', '#C6E78E'], // 自定义颜色
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const dataIndex = params[0].dataIndex;
              const year = result[dataIndex].year;
              const month = result[dataIndex].month;
              const date = result[dataIndex].date;
              const date1 = dayjs(date).format("MM-DD");
              const messageCount = result[dataIndex].messageCount;
              const yearOverYearChange = result[dataIndex].yearOverYearChange;
              const monthOverMonthChange = result[dataIndex].monthOverMonthChange;
              const lastDayMessageCount = result[dataIndex].lastDayMessageCount;
              const lastDayMonthMessageCount = result[dataIndex].lastDayMonthMessageCount;
              const dayOverDayChange = result[dataIndex].dayOverDayChange;
              const dayMonthOverDayMonthChange = result[dataIndex].dayMonthOverDayMonthChange;
              const lastYearCount = result[dataIndex].lastYearCount;
              const yearChange = result[dataIndex].yearChange;

              switch (self.selectedButtonType) {
                case 'date':
                  return `
                  ${date1}<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(139,220,165);"></span>消息数: ${messageCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>同比: ${dayMonthOverDayMonthChange}%<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${dayOverDayChange}%`;
                  break;
                case 'month':
                  return `
                  ${year}-${month}<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(139,220,165);"></span>消息数: ${messageCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>同比: ${yearOverYearChange}%<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${monthOverMonthChange}%`;
                  break;
                case 'year':
                  return `
                  ${year}<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(139,220,165);"></span>消息数: ${messageCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${yearChange}%`;
                  break;
                default:
                  break;
              }
            },
            padding:20,
            margin: 10,
            backgroundColor: 'rgba(242,244,245,0.8)', // 调整背景颜色，增加透明度
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: '5%',
            top: '5%',
            containLabel: true
          },
          // result.map(item => `${item.year}-${item.month}`)
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: {
              show: true,
              lineStyle: {
                // color: 'red', // 横坐标轴颜色
                width: 1 // 横坐标轴宽度
              }
            },

          },
          yAxis: {
            type: 'value',
            interval: 50, // 设置纵坐标间隔
            name:'个',
            nameTextStyle:{
              fontSize:'12',

            },

          },
          series: [
            {
              data: result.map(item => item.messageCount),
              type: 'bar',
              barWidth:35,
              itemStyle: {
                // 第一个柱状图使用第一种颜色
                color: function(params) {
                  return params.dataIndex % 2 === 0 ? '#758afe' : '#abb8fe';
                },
                // 设置顶部圆弧样式
                barBorderRadius: [10, 10, 0, 0],


              }
            },

          ]
        };

        chart.setOption(option);
      });
    },

    // 初始化左侧折线图
    initChartL2() {
      // 保存正确的上下文
      const self = this;
      // 直接初始化，不需要检查实例是否存在
      document.getElementById('chartL2').removeAttribute('_echarts_instance_');
      let chartL2 = document.getElementById('chartL2');
      const windowHeight = window.innerHeight; // 获取窗口高度
      chartL2.style.height = `${windowHeight * 0.3}px`;
      // chartL2.style.height = '200px';
      chartL2.style.width='100%'
      const chart = echarts.init(chartL2);

      // 在这里调用 queryGroupData 方法获取群组数据
      this.queryGrowGroupRateData().then((result) => {
        let xAxisData;
        switch (self.selectedButtonType) {

          case 'date':
            // 如果选择按日，横坐标为月-日
            xAxisData = result.map(item => dayjs(item.date).format("MM-DD"));
            break;
          case 'month':
            // 如果选择按月，横坐标为年-月
            xAxisData = result.map(item => `${item.year}-${item.month}`);
            break;
          case 'year':
            // 如果选择按年，横坐标为年
            xAxisData = result.map(item => item.year);
            break;
          default:
            xAxisData = [];
        }
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line',
              lineStyle: {
                type: 'solid', // 设置为实线
                width:'2'
              }
            },
            formatter: function(params) {
              const dataIndex = params[0].dataIndex;
              const year = result[dataIndex].year;
              const month = result[dataIndex].month;
              const date = result[dataIndex].date;
              const date1 = dayjs(date).format("MM-DD");
              const groupCount = result[dataIndex].groupCount;
              const activeGroupCount = result[dataIndex].activeGroupCount;
              //按日
              const dayOverDayGroupChange = result[dataIndex].dayOverDayGroupChange;
              const dayMonthOverDayMonthGroupChange = result[dataIndex].dayMonthOverDayMonthGroupChange;
              const dayOverDayActiveGroupChange = result[dataIndex].dayOverDayActiveGroupChange;
              const dayMonthOverDayMonthActiveGroupChange = result[dataIndex].dayMonthOverDayMonthActiveGroupChange;
              //按月
              const yearOverYearGroupChange = result[dataIndex].yearOverYearGroupChange;
              const monthOverMonthGroupChange = result[dataIndex].monthOverMonthGroupChange;
              const yearOverYearActiveGroupChange = result[dataIndex].yearOverYearActiveGroupChange;
              const monthOverMonthActiveGroupChange = result[dataIndex].monthOverMonthActiveGroupChange;
              //按年
              const yearGpChange = result[dataIndex].yearGpChange;
              const yearAGpChange = result[dataIndex].yearAGpChange;
              switch (self.selectedButtonType) {
                case 'date':
                  return `
                  ${date1}<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:#3A84FF;"></span>群组数: ${groupCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>同比: ${dayMonthOverDayMonthGroupChange}%<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${dayOverDayGroupChange}%<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(139,220,165);"></span>活跃群组数:${activeGroupCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>同比: ${dayMonthOverDayMonthActiveGroupChange}%<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${dayOverDayActiveGroupChange}%<br>`;
                  break;
                case 'month':
                  return `
                  ${year}-${month}<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:#3A84FF;"></span>群组数: ${groupCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>同比: ${yearOverYearGroupChange}%<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${monthOverMonthGroupChange}%<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(139,220,165);"></span>活跃群组数:${activeGroupCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>同比: ${yearOverYearActiveGroupChange}%<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${monthOverMonthActiveGroupChange}%<br>`;
                  break;
                case 'year':
                  return `
                  ${year}<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:#3A84FF;"></span>群组数: ${groupCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${yearGpChange}%<br>
                  <span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:rgb(139,220,165);"></span>活跃群组数:${activeGroupCount} 个<br>
                  <span style="display:inline-block;margin-right:4px;width:10px;height:10px;"></span>环比: ${yearAGpChange}%<br>`;
                  break;
                default:
                  break;
              }
            },
            padding:20,
            margin: 10,
            backgroundColor: 'rgba(242,244,245,0.8)', // 调整背景颜色，增加透明度

          },
          legend: {
            data: ['群组数', '活跃群组数'],
          },
          grid: {
            left: '5%',
            right: '2%',
            bottom: '3%',
            top:'10%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data:  xAxisData,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '群组数',
              type: 'line',
              itemStyle: {
                normal: {
                  color:'#3A84FF',
                  lineStyle: {
                    color: "#47b4fd",
                    width:2
                  },
                  areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                      offset: 0,
                      color: 'rgba(156,214,254,0)'
                    }, {
                      offset: 1,
                      color: 'rgb(156,214,254,0.5)'
                    }]),
                  }
                }
              },
              data: result.map(item => item.groupCount),
            },
            // 添加活跃群组数的配置
            {
              name: '活跃群组数',
              type: 'line',
              itemStyle: {
                normal: {
                  color:'rgb(174,228,196)',
                  lineStyle: {
                    color: "rgb(139,220,165)",
                    width:2
                  },
                  areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                      offset: 0,
                      color: 'rgba(139,220,165,0)'
                    }, {
                      offset: 1,
                      color: 'rgb(139,220,165,0.5)'
                    }]),
                  }
                }
              },
              data: result.map(item => item.activeGroupCount),
            },
          ],
        };

        chart.setOption(option);
      });
    },
    //初始化左侧横向柱状图
    initChartL3() {
      // 直接初始化，不需要检查实例是否存在
      document.getElementById("chartL3").removeAttribute('_echarts_instance_');
      let chartL3 = document.getElementById("chartL3");
      const windowHeight = window.innerHeight; // 获取窗口高度
      chartL3.style.height = `${windowHeight * 0.3}px`;
      // chartL3.style.height = "200px";
      const chart = echarts.init(chartL3);

      // 调用 queryActiveGroupData 方法获取数据
      this.queryActiveGroupData().then(result => {
        const option = {

          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(242,244,245,0.8)', // 调整背景颜色，增加透明度
          },
          title: [{
            // 在右下角添加单位说明
            text: '单位：个',
            right: '0',
            bottom: '0',
            textStyle: {
              fontSize: 12,
              color: '#333'
            }
          },
            {
              text: '{a|     群组名称                     消息数}',
              left: '0',  // 将整体标题居中
              top: '1%',
              textStyle: {
                fontSize: 14,
                color: '#333',
                rich: {
                  a: {
                    backgroundColor: 'rgba(171, 222, 255, 0.1)', // 这里设置您想要的背景颜色
                    width: 1000, // 这里设置背景的总宽度，应该足够覆盖"群组名称"和"消息数"
                    height: 30, // 这里设置背景的高度
                    align: 'left' // 这里设置文本的对齐方式
                  }
                }
              }
            }

          ],
          grid: {
            left: '1%',
            right: '5%',
            bottom: '2%',
            top:'20%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
             show:false,
            boundaryGap: [0, 0.01],
          },
          yAxis: {
             // name:'群组名',
            type: 'category',
            inverse: true, // 反转排列顺序
            data: result.map(item => item.groupName),  // 群组名称
            axisLabel: {
              inside: false,  // 标签位置设置在坐标轴外侧
              align: 'center',  // 文本居中对齐
              formatter: function(value) {
                // 格式化函数，value为每个标签的原始值
                return value.length > 7 ? value.slice(0, 7) + '...' : value;  // 超过7个字符的文本显示省略号
              },
              margin: 40  // 增加标签与图表的间距
            },

          },
          series: [
            {
              name: '消息数量',
              type: 'bar',
              barWidth:20,
              data: result.map(item => item.messagesCount),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(
                    0, 0, 1, 0,
                    [
                      { offset: 0, color: '#0498fb' }, // 渐变色起始颜色
                      { offset: 1, color: '#1fccea' } // 渐变色结束颜色
                    ]
                ),
                // 设置顶部圆弧样式
                barBorderRadius: [0, 10, 10, 0],
              },
              label: {
                show: true,
                position: 'inside', // 在柱子内部显示
                formatter: '{c}', // 显示数据值
              },
            }
          ]
        };
        chart.setOption(option);
      });
    },

    //初始化右侧扇形图
    initChartL4() {
      // 直接初始化，不需要检查实例是否存在
      document.getElementById("chartL4").removeAttribute('_echarts_instance_');
      let chartL4 = document.getElementById("chartL4");
      const windowHeight = window.innerHeight; // 获取窗口高度
      chartL4.style.height = `${windowHeight * 0.3}px`;
      // chartL4.style.height = "230px";
      chartL4.style.width= "100%"
      const chart = echarts.init(chartL4);
      // 发起 HTTP 请求获取数据
      this.queryDeptPercentage().then(result => {
        // 选出前6个部门
        const topDepartments = result.slice(0, 6);
        // 计算"其他部门"的总人数
        const otherTotal = result.slice(6).reduce((acc, curr) => acc + curr.value, 0);
        // 如果有"其他部门"，则添加到数据中
        if (otherTotal > 0) {
          topDepartments.push({ name: '其他部门', value: otherTotal });
        }
        // if(result.count)
        // 处理后端返回的数据 过滤掉值为0的数据
        // const filteredData = result.filter(item => item.value !== 0); // Filter out items with value 0
        const pieData = topDepartments.map(item => ({
          value: item.value,
          name: item.name,

        }));

        const option = {
          color: ['#DEC4E1', '#C6E78E', '#80D019', '#fdcbcb', '#fd8568','#fdcd37','#fbe102','#99b8ee'], // 自定义颜色

          tooltip: {
            trigger: 'item',
            formatter: '{b}: {d}% ({c}人)' // 显示百分比和人数
          },
          legend: {
            top: '10%',
            orient: 'vertical',
            left: '65%',
            // // 在legend中显示人数
            // formatter: function (name) {
            //   const dataItem = filteredData.find(item => item.name === name);
            //   return `${name}            ${dataItem.value}人`;
            // },
            // 在legend中显示人数
            formatter: function (name, index) {
              const dataItem = topDepartments.find(item => item.name === name);
              // const color = colorBg(index);
              // return `${name}<span style="color: red">${dataItem.value}人</span>`;
              // return name + '<span style="color: ' + color + '">' + dataItem.value + '人</span>';
              return `${name}               ${dataItem.value}人`;
            },
          },
          series: [
            {
              // name: '全体用户',
              type: 'pie',
              radius: ['50%', '80%'],
              center: ['36%', '50%'],
              avoidLabelOverlap: true,
              itemStyle: {
                borderRadius: 1,
                borderColor: '#fff',
                borderWidth: 2
              },
              label:{
                show:false,
                formatter: ' {d}% ' // 显示百分比和人数
              },

              emphasis: {
                label: {
                  show: true,
                  fontSize: 14,// 调整强调时的标签字体大小
                  fontWeight: 'bold'
                }
              },


              data:pieData,


            }
          ]
        };
        chart.setOption(option);
      });
    },

    // 格式化日期的辅助方法
    formatDate(dateString) {
      if (dateString) {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else {
        return null;
      }
    },


    },



}

function getDefaultDateRange(type) {
  const now = dayjs();
  switch (type) {
    case 'date':
      return [now.subtract(1, 'month'), now];
    case 'month':
      return [now.subtract(1, 'year').startOf('month'), now.endOf('month')];
    case 'year':
      return [now.subtract(5, 'year'), now];
    default:
      return [null, null];
  }
}
</script>

<style scoped>
.active-button {
  background-color: #1890ff; /* 你想要的选中时的颜色 */
  color: #fff; /* 选中时的文字颜色 */
}
.stats-area {
  display: flex;
  justify-content: space-around;
}


.custom-statistic {
  font-weight: bold;
  color: #fbb011;

}

.stats-area a-card {
  margin: 0 10px; /* 调整 a-card 的边距 */
}

.header-container {
  display: flex;
  align-items: center; /* 将项目垂直居中对齐 */
}

.header-container img {
  margin-right: 1px; /* 根据需要调整边距 */
}

/deep/ .ant-card .ant-card-body {
  display: flex;
  align-items: center;
  padding: 15px;
}
/deep/ .ant-statistic .ant-statistic-content {
  text-align: center;
}

/deep/ .ant-table-wrapper tfoot>tr>td {
  padding: 5px;

}
/* 设置表格头部背景色 */
/deep/ .ant-table-thead > tr > th {
  background-color: rgba(171, 222, 255, 0.1); /* 这里设置你想要的颜色 */
}



/* 单元格样式 */
/deep/ .ant-table-tbody > tr > td {
  border-bottom: 0; /* 移除单元格底部边框 */
}






/* 确保滚动时阴影不被剪切 */
/deep/ .ant-table-body {
  overflow: visible;
}
/deep/ .column-name {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.table-class {
  height: 100%;

}

.app-container {
  padding: 20px;
}
</style>
